﻿/*
 LinkedResource lrImage = new LinkedResource(@"d:\blogo.jpg", "image/jpg");
            lrImage.ContentId = "weblogo";
            List<LinkedResource> list=new List<LinkedResource>();
            list.Add(lrImage);
            string htmlBodyContent = "如果你的看到<b>这个</b>， 说明你是在以 <span style=\"color:red\">HTML</span> 格式查看邮件<br><br>";
            htmlBodyContent += "<a href=\"http://www.zu14.cn/\">真有意思网</a> <img src=\"cid:weblogo\">";

            string xx = Mail.SendMail("solucky2008@gmail.com", "solucky2008@gmail.com", "测试", htmlBodyContent,list);
           Response.Write(xx);
 */
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Mail;
using System.Configuration;
using System.Collections;
using System.Web.Mail;
using System.Web;
using System.Threading;

namespace IHISCETeim.SendEMailSvr
{
    public class Mail
    {
        protected const string vbCrlf = "\n";
        protected const string glbEmailRegEx = @"\b[a-zA-Z0-9._%\-+']+@[a-zA-Z0-9.\-]+\.[a-zA-Z]{2,4}\b";
        public static string ConvertToText(string sHTML)
        {
            string sContent = sHTML;
            sContent = sContent.Replace("<br />", vbCrlf);
            sContent = sContent.Replace("<br>", vbCrlf);
            //sContent = StringHelper.FormatText(sContent, true);
            return sContent;
            //return StringHelper.StripTags(sContent, true);
        }

        public static bool IsHTMLMail(string Body)
        {
            return System.Text.RegularExpressions.Regex.IsMatch(Body, "<[^>]*>");
        }

        public static bool IsValidEmailAddress(string Email)
        {
            string pattern = glbEmailRegEx;
            return System.Text.RegularExpressions.Regex.Match(Email, pattern).Success;
        }
        public static string SendMail(string MailTo, string Subject, string Body)
        {
            List<Attachment> Attachments = new List<Attachment>();
            List<LinkedResource> LinkedResources = new List<LinkedResource>();

            //  Encoding gb2312 = Encoding.GetEncoding("GB2312");


            return SendMail("", MailTo, "", "", "", System.Web.Mail.MailPriority.Normal, Subject, Body, Attachments, LinkedResources);
        }
        /// <summary>
        /// 发送一般EMAIL
        /// </summary>
        /// <param name="MailFrom"></param>
        /// <param name="MailTo"></param>
        /// <param name="Subject"></param>
        /// <param name="Body"></param>
        /// <returns></returns>
        public static string SendMail(string MailFrom, string MailTo, string Subject, string Body)
        {
            List<Attachment> Attachments = new List<Attachment>();
            List<LinkedResource> LinkedResources = new List<LinkedResource>();
            return SendMail(MailFrom, MailTo, "", "", "", System.Web.Mail.MailPriority.Normal, Subject, Body, Attachments, LinkedResources);
        }
        /// <summary>
        /// 带有内嵌资源的EMAIL
        /// </summary>
        /// <param name="MailFrom"></param>
        /// <param name="MailTo"></param>
        /// <param name="Subject"></param>
        /// <param name="Body"></param>
        /// <param name="LinkedResources"></param>
        /// <returns></returns>
        public static string SendMail(string MailFrom, string MailTo, string Subject, string Body, List<LinkedResource> LinkedResources)
        {
            List<Attachment> Attachments = new List<Attachment>();
            return SendMail(MailFrom, MailTo, "", "", "", System.Web.Mail.MailPriority.Normal, Subject, Body, Attachments, LinkedResources);
        }

        public static string SendMail(string MailFrom, string MailTo, string Cc, string Bcc, string ReplyTo, System.Web.Mail.MailPriority Priority, string Subject, string Body, List<Attachment> Attachments, List<LinkedResource> LinkedResources)
        {
            /*读取WEB.CONFIG中自定义配置节的内容*/
            try
            {
                Hashtable mailServer = (Hashtable)ConfigurationManager.GetSection("mailServer");

                string SMTPServer = mailServer["SMTPServer"].ToString();/*SMTP服务器.如果需要端口的话可用如下格式 smtp.gmail.com:465*/
                string SMTPAuthentication = mailServer["SMTPAuthentication"].ToString();/*验证发件人身份的凭据 0:不设置1:设置用于验证发件人身份的凭据 2:使用默认*/
                string SMTPUsername = mailServer["SMTPUsername"].ToString();
                string SMTPPassword = mailServer["SMTPPassword"].ToString();
                bool SMTPEnableSSL = Convert.ToBoolean(mailServer["SMTPEnableSSL"].ToString());/*是否使用安全套接字层 (SSL) 加密连接*/
                if (string.IsNullOrEmpty(MailFrom))
                    MailFrom = SMTPUsername;
                return SendMail(MailFrom, MailTo, Cc, Bcc, ReplyTo, Priority, Subject, Body, Attachments, LinkedResources, SMTPServer, SMTPAuthentication, SMTPUsername, SMTPPassword, SMTPEnableSSL);
            }
            catch
            {
                return "无法读取app.Config中对邮件的自定义配置信息";
            }

        }
        public static string QltySendMail(string MailTo, string Subject, string Body)
        {
            List<Attachment> Attachments = new List<Attachment>();
            List<LinkedResource> LinkedResources = new List<LinkedResource>();
            /*读取WEB.CONFIG中自定义配置节的内容*/
            try
            {
                Hashtable QltyMailServer = (Hashtable)ConfigurationManager.GetSection("QltyMailServer");

                string SMTPServer = QltyMailServer["SMTPServer"].ToString();/*SMTP服务器.如果需要端口的话可用如下格式 smtp.gmail.com:465*/
                string SMTPAuthentication = QltyMailServer["SMTPAuthentication"].ToString();/*验证发件人身份的凭据 0:不设置1:设置用于验证发件人身份的凭据 2:使用默认*/
                string SMTPUsername = QltyMailServer["SMTPUsername"].ToString();
                string SMTPPassword = QltyMailServer["SMTPPassword"].ToString();
                bool SMTPEnableSSL = Convert.ToBoolean(QltyMailServer["SMTPEnableSSL"].ToString());/*是否使用安全套接字层 (SSL) 加密连接*/
                //if (string.IsNullOrEmpty(MailFrom))
                //    MailFrom = SMTPUsername;
                return SendMail(SMTPUsername, MailTo, "", "", "",  System.Web.Mail.MailPriority.Normal, Subject, Body, Attachments, LinkedResources, SMTPServer, SMTPAuthentication, SMTPUsername, SMTPPassword, SMTPEnableSSL);
            }
            catch
            {
                return "无法读取app.Config中对邮件 QltyMailServer 的自定义配置信息";
            }

        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="MailFrom"></param>
        /// <param name="MailTo"></param>
        /// <param name="Cc">抄送</param>
        /// <param name="Bcc">密件抄送</param>
        /// <param name="ReplyTo">回复地址</param>
        /// <param name="Priority">设置此电子邮件的优先级</param>
        /// <param name="Subject"></param>
        /// <param name="BodyFormat">提供电子邮件格式</param>
        /// <param name="BodyEncoding"></param>
        /// <param name="Body"></param>
        /// <param name="Attachments"></param>
        /// <param name="LinkedResources">内嵌资源</param>
        /// <param name="SMTPServer"></param>
        /// <param name="SMTPAuthentication"></param>
        /// <param name="SMTPUsername"></param>
        /// <param name="SMTPPassword"></param>
        /// <param name="SMTPEnableSSL"></param>
        /// <returns></returns>
        public static string SendMail(string MailFrom, string MailTo, string Cc, string Bcc, string ReplyTo, System.Web.Mail.MailPriority Priority, string Subject, string Body,
List<Attachment> Attachments, List<LinkedResource> LinkedResources, string SMTPServer, string SMTPAuthentication, string SMTPUsername, string SMTPPassword, bool SMTPEnableSSL)
        {

            System.Text.Encoding BodyEncoding = Encoding.GetEncoding(936);

            string functionReturnValue = null;
            functionReturnValue = "";

            if (!IsValidEmailAddress(MailFrom))
            {
                return "邮件发送地址错误";
            }


            // translate semi-colon delimiters to commas as ASP.NET 2.0 does not support semi-colons 
            MailTo = MailTo.Replace(";", ",");
            Cc = Cc.Replace(";", ",");
            Bcc = Bcc.Replace(";", ",");

            System.Net.Mail.MailMessage objMail = null;
            try
            {
                objMail = new System.Net.Mail.MailMessage();
                objMail.From = new MailAddress(MailFrom);
                if (!string.IsNullOrEmpty(MailTo))
                {
                    foreach (string item in MailTo.Split(','))
                    {
                        if (!string.IsNullOrEmpty(item))
                            objMail.To.Add(item);
                    }
                }
                if (!string.IsNullOrEmpty(Cc))
                {
                    objMail.CC.Add(Cc);
                }
                if (!string.IsNullOrEmpty(Bcc))
                {
                    objMail.Bcc.Add(Bcc);
                }
                if (ReplyTo != string.Empty) objMail.ReplyTo = new System.Net.Mail.MailAddress(ReplyTo);
                objMail.Priority = System.Net.Mail.MailPriority.Normal;
                objMail.IsBodyHtml = IsHTMLMail(Body);

                foreach (Attachment myAtt in Attachments)
                {
                    objMail.Attachments.Add(myAtt);
                }

                // message 
                objMail.SubjectEncoding = BodyEncoding;
                objMail.Subject = Subject;
                objMail.BodyEncoding = BodyEncoding;
                objMail.Body = Body;
                //System.Net.Mail.AlternateView PlainView = System.Net.Mail.AlternateView.CreateAlternateViewFromString(ConvertToText(Body), null, "text/plain");
                //objMail.AlternateViews.Add(PlainView);

                //if body contains html, add html part 
                //if (objMail.IsBodyHtml)
                //{

                //    System.Net.Mail.AlternateView HTMLView = System.Net.Mail.AlternateView.CreateAlternateViewFromString(Body, null, "text/html");

                //    foreach (LinkedResource lrOjb in LinkedResources)
                //    {
                //        HTMLView.LinkedResources.Add(lrOjb);
                //    }
                //    objMail.AlternateViews.Add(HTMLView);
                //}
            }
            catch (Exception objException)
            {
                functionReturnValue = MailTo + ": " + objException.Message;
            }

            if (objMail != null)
            {

                // external SMTP server alternate port 
                int SmtpPort = -1;
                int portPos = SMTPServer.IndexOf(":");
                if (portPos > -1)
                {
                    SmtpPort = Int32.Parse(SMTPServer.Substring(portPos + 1, SMTPServer.Length - portPos - 1));
                    SMTPServer = SMTPServer.Substring(0, portPos);
                }

                System.Net.Mail.SmtpClient smtpClient = new System.Net.Mail.SmtpClient();

                try
                {
                    if (!string.IsNullOrEmpty(SMTPServer))
                    {
                        smtpClient.Host = SMTPServer;
                        if (SmtpPort > -1)
                        {
                            smtpClient.Port = SmtpPort;
                        }
                        switch (SMTPAuthentication)
                        {
                            case "":
                            case "0":
                                // anonymous 
                                break;
                            case "1":
                                // basic 
                                if (!string.IsNullOrEmpty(SMTPUsername) & !string.IsNullOrEmpty(SMTPPassword))
                                {
                                    smtpClient.UseDefaultCredentials = false;
                                    smtpClient.Credentials = new System.Net.NetworkCredential(SMTPUsername, SMTPPassword);
                                }

                                break;
                            case "2":
                                // NTLM 
                                smtpClient.UseDefaultCredentials = true;
                                break;
                        }
                    }
                    smtpClient.EnableSsl = SMTPEnableSSL;

                    smtpClient.Send(objMail);
                    functionReturnValue = "";
                }
                catch (SmtpFailedRecipientException exc)
                {
                    functionReturnValue = HttpContext.Current.Server.HtmlEncode(exc.FailedRecipient);

                }
                catch (SmtpException exc)
                {
                    functionReturnValue = exc.Message + "SMTP配置有问题.请检查配置信息";
                }
                catch (Exception objException)
                {
                    // mail configuration problem 
                    if ((objException.InnerException != null))
                    {
                        functionReturnValue = objException.InnerException.Message;
                    }
                    else
                    {
                        functionReturnValue = objException.Message;
                    }
                }
                finally
                {
                    Thread.Sleep(2000);
                    objMail.Dispose();
                }
            }

            return functionReturnValue;
        }

    }
}
